package com.riaevolution.utils {
	import flash.events.EventDispatcher;
	import flash.net.LocalConnection;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;

	[Event(name="applicationAlreadyRunning", type="com.riaevolution.utils.ApplicationBrowserEvent")]
	[Event(name="applicationUniqueIsRunning", type="com.riaevolution.utils.ApplicationBrowserEvent")]
	/**
	 * This class help you to avoid multiple instances of the same application running on many tabs or browsers.
	 *
	 * <b>Example</b>
	 * <listing>
	 * &lt;ria:ApplicationBrowserSingleton id="browserSingleton"
	 * 		applicationId="very_secret_code_id_for_your_app"
	 * 		applicationUniqueIsRunning="applicationUniqueIsRunningHandler(event)"
	 * 		applicationAlreadyRunning="applicationAlreadyRunningHandler(event)"/&gt;
	 * </listing>
	 * */
	public class ApplicationBrowserSingleton extends EventDispatcher {

		private var pingConnection:LocalConnection;
		private var _applicationID:String;

		/**
		 * Constructor
		 * @param uniqueid
		 */
		public function ApplicationBrowserSingleton(uniqueid:String=null) {
			super(null);
			if (uniqueid != null) {
				applicationId=uniqueid;
			}
		}
		private var creatTO:int;

		/**
		 * Set the application ID this will perform a validation to
		 * uniquely identify your app throug many instances opened on the browser.
		 *
		 * @param value
		 */
		public function set applicationId(value:String):void {
			this._applicationID=value;
			if (creatTO) {
				clearTimeout(creatTO);
			}
			creatTO=setTimeout(createLocalConnection, 1000);
		}

		/**
		 * Test method
		 */
		protected function createLocalConnection():void {
			pingConnection=new LocalConnection();
			pingConnection.client=this;
			var event:ApplicationBrowserEvent;
			try {
				pingConnection.connect(this._applicationID);
				event=new ApplicationBrowserEvent(ApplicationBrowserEvent.SUCCESS, this._applicationID + " running");
			}
			catch (error:Error) {
				event=new ApplicationBrowserEvent(ApplicationBrowserEvent.ERROR, this._applicationID + " already running")
			}
			dispatchEvent(event);
		}
	}
}